package sun.it.web;

import sun.it.domain.User;
import sun.it.service.UserService;
import sun.it.service.impl.UserServiceimpl;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter("/login.jsp")
public class AutoLoginFilter implements Filter {
    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request= (HttpServletRequest) req;
        HttpServletResponse response= (HttpServletResponse) resp;
        HttpSession session = request.getSession();
        UserService service= new UserServiceimpl();
        User user = (User) request.getSession().getAttribute("user");
        if(user!=null){
            User user1 = service.CheckLogin(user);
            if(user1!=null){
                session.setAttribute("user",user);
                session.setAttribute("username",user.getUsername());
                request.getRequestDispatcher("index.jsp").forward(request,response);
                //response.sendRedirect(request.getContextPath()+"/index.html");
            }else{
                request.setAttribute("error_msg","账号或密码错误!");
                request.getRequestDispatcher("login.jsp").forward(request,response);
                //response.sendRedirect(request.getContextPath()+"/login.html");
            }
        }
        chain.doFilter(request,resp);
    }

    public void init(FilterConfig config) throws ServletException {

    }

}
